package com.zhj.estest.client.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhj.estest.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class ESTest_Doc_Batch_Client {



    public static void main(String[] args) throws IOException {
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200, "http"))
        );

        // 批量插入数据
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON,"name","张三","sex","男","age",15));
        bulkRequest.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON,"name","李四","sex","女","age",18));
        bulkRequest.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON,"name","王五","sex","未知","age",25));
        bulkRequest.add(new IndexRequest().index("user").id("1007").source(XContentType.JSON,"name","张三"));
        bulkRequest.add(new IndexRequest().index("user").id("1008").source(XContentType.JSON,"name","李四"));
        bulkRequest.add(new IndexRequest().index("user").id("1009").source(XContentType.JSON,"name","王五"));
        BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("批量插入，时间：" + bulk.getTook());

        // 批量删除数据
        bulkRequest = new BulkRequest();
        bulkRequest.add(new DeleteRequest().index("user").id("1007"));
        bulkRequest.add(new DeleteRequest().index("user").id("1008"));
        bulkRequest.add(new DeleteRequest().index("user").id("1009"));
        bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("批量删除，时间：" + bulk.getTook());

        esClient.close();
    }
}
